import { defineStore } from 'pinia'
import { login, logout, getUserInfo } from '../servers/user'

export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户信息
    userInfo: null,
    // 登录状态
    isLoggedIn: false,
    // 登录令牌
    token: null,
    // 用户权限
    permissions: []
  }),

  getters: {
    // 获取用户名
    username: (state) => state.userInfo?.username || '',
    // 获取用户角色
    userRole: (state) => state.userInfo?.role || '',
    // 获取用户头像
    avatar: (state) => state.userInfo?.avatar || '',
    // 检查是否有特定权限
    hasPermission: (state) => (permission) => {
      return state.permissions.includes(permission)
    }
  },

  actions: {
    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = userInfo
      this.isLoggedIn = true
    },

    // 设置令牌
    setToken(token) {
      this.token = token
      // 保存到localStorage
      localStorage.setItem('token', token)
    },

    // 设置权限
    setPermissions(permissions) {
      this.permissions = permissions
    },

    // 登录
    async login(loginData) {
      try {
        const response = await login(loginData)
        
        if (response.success) {
          const { userInfo, token, permissions } = response.data
          
          // 保存用户信息
          this.setUserInfo(userInfo)
          this.setToken(token)
          this.setPermissions(permissions || [])
          
          // 根据记住我选项保存到不同存储
          if (loginData.rememberMe) {
            localStorage.setItem('userInfo', JSON.stringify(userInfo))
          } else {
            sessionStorage.setItem('userInfo', JSON.stringify(userInfo))
          }
          
          return { success: true, data: response.data }
        } else {
          return { success: false, message: response.message }
        }
      } catch (error) {
        console.error('登录失败:', error)
        return { success: false, message: '登录失败，请稍后重试' }
      }
    },

    // 登出
    async logout() {
      try {
        // 调用登出API
        await logout()
      } catch (error) {
        console.error('登出API调用失败:', error)
      } finally {
        // 清除本地状态
        this.clearUserData()
      }
    },

    // 清除用户数据
    clearUserData() {
      this.userInfo = null
      this.isLoggedIn = false
      this.token = null
      this.permissions = []
      
      // 清除本地存储
      localStorage.removeItem('userInfo')
      localStorage.removeItem('token')
      sessionStorage.removeItem('userInfo')
    },

    // 从本地存储恢复用户信息
    restoreUserInfo() {
      const userInfo = localStorage.getItem('userInfo') || sessionStorage.getItem('userInfo')
      const token = localStorage.getItem('token')
      
      if (userInfo && token) {
        try {
          const parsedUserInfo = JSON.parse(userInfo)
          this.setUserInfo(parsedUserInfo)
          this.setToken(token)
          return true
        } catch (error) {
          console.error('恢复用户信息失败:', error)
          this.clearUserData()
          return false
        }
      }
      
      return false
    },

    // 获取用户信息
    async fetchUserInfo() {
      try {
        const response = await getUserInfo()
        if (response.success) {
          this.setUserInfo(response.data)
          return response.data
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        // 如果获取用户信息失败，清除本地数据
        this.clearUserData()
      }
    },

    // 检查登录状态
    checkLoginStatus() {
      const userInfo = localStorage.getItem('userInfo') || sessionStorage.getItem('userInfo')
      const token = localStorage.getItem('token')
      
      if (userInfo && token) {
        this.restoreUserInfo()
        return true
      }
      
      return false
    }
  }
})
